package com.ctlele.team.space.fragment.impl;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.ctlele.team.space.R;
import com.ctlele.team.space.activity.impl.LoginActivity;
import com.ctlele.team.space.api.Api;
import com.ctlele.team.space.api.ApiStatusCode;
import com.ctlele.team.space.api.Apis;
import com.ctlele.team.space.entity.vo.BaseResponse;
import com.ctlele.team.space.entity.vo.UserVo;
import com.ctlele.team.space.entity.vo.resp.UserInfoResp;
import com.ctlele.team.space.fragment.BaseFragment;
import com.ctlele.team.space.util.ImageUtils;
import com.ctlele.team.space.util.VideoCacheUtils;
import com.ctlele.team.space.widget.dialog.MsgDialog;
import com.ctlele.team.space.widget.toast.IToast;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.concurrent.atomic.AtomicBoolean;

import okhttp3.Call;
import okhttp3.Response;

public class MyFragment extends BaseFragment {

    private static final String TAG = "MyFragment";

    private TextView mUsername;

    private TextView mNickname;

    private TextView mEmail;

    private ImageView mAvatar;

    private ImageView mSex;

    private View mExitLogin;

    private ImageView mIconLogin;

    private TextView mToLogin;

    private AtomicBoolean mIsLogin = new AtomicBoolean(false);

    private View mClearCache;

    public MyFragment() {
    }

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {
        mUsername = mRootView.findViewById(R.id.username);
        mNickname = mRootView.findViewById(R.id.nickname);
        mEmail = mRootView.findViewById(R.id.email);
        mAvatar = mRootView.findViewById(R.id.avatar);
        mSex = mRootView.findViewById(R.id.sex);
        mIconLogin = mRootView.findViewById(R.id.icon_login_or_exit);
        mToLogin = mRootView.findViewById(R.id.to_login);
        mExitLogin = mRootView.findViewById(R.id.exit_login_layout);
        mClearCache = mRootView.findViewById(R.id.clear_cache_layout);
    }

    @Override
    protected void initData() {
        mExitLogin.setOnClickListener(view -> {
            if (!mIsLogin.get()) {
                reload();
                turnTo(LoginActivity.class);
                return;
            }
            Api.get(getContext(), Apis.USER_EXIT_LOGIN, new ArrayList<>(), new Api.ApiCallback() {
                @Override
                public void onFailure(Context context, Call call, IOException e) {
                    Log.e(TAG, e.getMessage(), e);
                }

                @Override
                public void onResponse(Context context, Call call, Response response) throws IOException {
                    String res = response.body().string();
                    BaseResponse resp = JSON.parseObject(res, BaseResponse.class);
                    if (resp != null && resp.getCode().equals(ApiStatusCode.OK)) {
                        IToast.success(getContext(), "退出成功").andOnUiThread(() -> {
                            resetUserInfo();
                            reload();
                            turnTo(LoginActivity.class);
                        });
                    }
                }
            });
        });
        Api.get(getContext(), Apis.LOGIN_USER_INFO, new ArrayList<>(), new Api.ApiCallback() {
            @Override
            public void onFailure(Context context, Call call, IOException e) {
                Log.e(TAG, e.getMessage(), e);
                reload();
            }

            @Override
            public void onResponse(Context context, Call call, Response response) throws IOException {
                String res = response.body().string();
                UserInfoResp resp = JSON.parseObject(res, UserInfoResp.class);
                if (resp != null && resp.getCode().equals(ApiStatusCode.OK)) {
                    UserVo userVo = resp.getData();
                    getActivity().runOnUiThread(() -> {
                        mIsLogin.set(true);
                        mToLogin.setText("退出登录");
                        mIconLogin.setImageResource(R.mipmap.exit_login);
                        mUsername.setText(userVo.getUsername());
                        mNickname.setText(userVo.getNickname());
                        mEmail.setText(userVo.getEmail());
                        if (!TextUtils.isEmpty(userVo.getAvatar()) &&
                                userVo.getAvatar().startsWith("http")) {
                            Picasso.with(getContext())
                                    .load(userVo.getAvatar())
                                    .transform(ImageUtils.getCircleImageTransformation())
                                    .into(mAvatar);
                        } else {
                            mAvatar.setImageResource(R.mipmap.default_user);
                        }
                        if (userVo.getSex() == 1) {
                            mSex.setImageResource(R.mipmap.icon_man);
                        } else {
                            mSex.setImageResource(R.mipmap.icon_women);
                        }
                    });
                } else {
                    reload();
                }
            }
        });

        mClearCache.setOnClickListener(view -> {
            try {
                VideoCacheUtils.cleanVideoCacheDir(this.getContext());
                Log.i(TAG, "clear cache success");
                IToast.success(getContext(), "缓存清理成功");
            } catch (Exception e) {
                Log.e(TAG, e.getMessage(), e);
                IToast.fail(getContext(), "缓存清理失败");
            }
        });
    }

    private void resetUserInfo() {
        getActivity().runOnUiThread(() -> {
            mUsername.setText("用户名");
            mNickname.setText("昵称");
            mEmail.setText("xxxxx@xx.com");
            mAvatar.setImageResource(R.mipmap.default_user);
            mSex.setImageResource(R.mipmap.icon_man);
            mIsLogin.set(false);
            mToLogin.setText("点击登录");
            mIconLogin.setImageResource(R.mipmap.icon_login);
        });
    }
}